package it.mp.multitask;

import it.mp.multitask.bean.App;
import it.mp.multitask.factory.Style;
import it.mp.multitask.factory.StyleFactory;
import it.mp.multitask.utility.music.MusicUtils;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {

	protected static final String SP_OPTIONS = "SP_OPTIONS";
	protected static final String PACKAGE_NAME = "PACKAGE_NAME->";
	private static final String MESSAGGIO_LETTO = "MESSAGGIO_LETTO->";
	public static final String PREF_KILL_SENZA_CONFERMA = "pref_kill_question";
	public static final String PREF_APP_SERVICE = "pref_service";
	public static final String PREF_APP_RUNNING = "pref_running";
	public static final String PREF_APP_RECENTLY = "pref_recently";
	public static final String PREF_THEME = "pref_background_theme";
	public static final String CLOSE_ON_START_APPLICATION = "close_on_start_application";

	private SharedPreferences prefs;

	public OnClickListener oclStartOptionPanel = new OnClickListener() {

		public void onClick(View v) {
		}

	};

	public OnClickListener oclPlay = new OnClickListener() {
		public void onClick(View arg0) {
			if (MusicUtils.sService != null) {
				try {
					if (MusicUtils.sService.isPlaying()) {
						MusicUtils.sService.pause();
						ImageView iv = (ImageView) Main.this.findViewById(R.id.IV_play);
						iv.setImageResource(R.drawable.pause_button);
					} else {
						MusicUtils.sService.play();
						ImageView iv = (ImageView) Main.this.findViewById(R.id.IV_play);
						iv.setImageResource(R.drawable.play_button);
					}
				} catch (RemoteException e) {
				}
			}
		}
	};
	public OnClickListener oclNext = new OnClickListener() {
		public void onClick(View arg0) {
			if (MusicUtils.sService != null) {
				try {
					MusicUtils.sService.next();
					ImageView iv = (ImageView) Main.this.findViewById(R.id.IV_play);
					iv.setImageResource(R.drawable.play_button);
				} catch (RemoteException e) {
				}
			}
		}
	};
	public OnClickListener oclPrev = new OnClickListener() {
		public void onClick(View arg0) {
			if (MusicUtils.sService != null) {
				try {
					MusicUtils.sService.prev();
					ImageView iv = (ImageView) Main.this.findViewById(R.id.IV_play);
					iv.setImageResource(R.drawable.play_button);
				} catch (RemoteException e) {
				}
			}
		}
	};
	public OnClickListener oclStartActivity = new OnClickListener() {
		public void onClick(View v) {
			App app = (App) v.getTag();
			prepareStartActivity(app);
		}
	};

	public OnLongClickListener oclKillActivity = new OnLongClickListener() {
		public boolean onLongClick(View v) {
			App app = (App) v.getTag();
			prepareKillActivity(app);
			return true;
		}

	};
	public OnClickListener oclKillAllActivity = new OnClickListener() {
		public void onClick(View v) {
			int NUMERO_PROCESSI_RUNNING = Integer.parseInt(prefs.getString(getResources().getString(R.string.App_running_number), "10"));
			final ActivityManager activityManager = (ActivityManager) Main.this.getSystemService(ACTIVITY_SERVICE);
			List<RunningTaskInfo> procInfos = activityManager.getRunningTasks(NUMERO_PROCESSI_RUNNING);
			String packageName;
			for (RunningTaskInfo rti : procInfos) {
				packageName = rti.baseActivity.getPackageName();
				if (prefs.getBoolean(packageName, false)) {

				} else {
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
						Class<? extends ActivityManager> dummyClass = activityManager.getClass();
						Class<?>[] partypes = new Class<?>[]{String.class};
						Method meth;
						try {
							meth = dummyClass.getMethod("killBackgroundProcesses", partypes);
							Object[] arglist = new Object[]{packageName};
							meth.invoke(activityManager, arglist);
						} catch (Exception e) {

						}
					} else {
						activityManager.restartPackage(packageName);
					}
				}
			}
			crea(Integer.parseInt(prefs.getString(getResources().getString(R.string.theme_main_new), "0")));
		}

	};
	private BitmapDrawable bmpCestino;
	private int dimensioneSchermo;
	public GestureDetector gestureDetector;

	private void onCreate() {
		onCreate(null);
		Editor editor = prefs.edit();
		editor.putBoolean(getResources().getString(R.string.mtm_on_home), true);
		editor.commit();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// android.os.Debug.startMethodTracing("MTM_1");

		super.onCreate(savedInstanceState);

		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		if (!prefs.getBoolean(Main.MESSAGGIO_LETTO, false)) {
			new InformationAlert(this, true).show();
		}

		if (prefs.getString(getResources().getString(R.string.Apps_list_preferred), "").equals("")) {
			Map<String, ?> preferredApps = prefs.getAll();
			Iterator<String> iterator = preferredApps.keySet().iterator();
			String chiave;
			Editor editor = prefs.edit();
			while (iterator.hasNext()) {
				chiave = iterator.next();
				if (chiave.startsWith(Setup.PREFIX_PREFERRED_APPS)) {
					editor.remove(chiave);
				}
			}
			editor.putString(getResources().getString(R.string.Apps_list_preferred), ";");
			editor.commit();
		}
		bmpCestino = (BitmapDrawable) getResources().getDrawable(R.drawable.recycle);
		dimensioneSchermo = getWindowManager().getDefaultDisplay().getWidth();

		crea(Integer.parseInt(prefs.getString(getResources().getString(R.string.theme_main_new), "0")));

		Editor editor = prefs.edit();
		editor.putBoolean(getResources().getString(R.string.mtm_on_home), true);
		editor.commit();
		// android.os.Debug.stopMethodTracing();
	}

	private void crea(int standardScreen) {
		int NUMERO_PROCESSI_RUNNING = 10;

		try {
			NUMERO_PROCESSI_RUNNING = Integer.parseInt(prefs.getString(getResources().getString(R.string.App_running_number), "10"));
		} catch (Exception e) {

		}

		int NUMERO_PROCESSI_RECENTLY = 10;
		try {
			NUMERO_PROCESSI_RECENTLY = Integer.parseInt(prefs.getString(getResources().getString(R.string.App_recently_number), "15"));
		} catch (Exception e) {

		}

		int NUMERO_PROCESSI_SERVICE = 10;
		try {
			NUMERO_PROCESSI_SERVICE = Integer.parseInt(prefs.getString(getResources().getString(R.string.App_service_number), "10"));
		} catch (Exception e) {

		}

		int margin = 0;
		try {
			margin = Integer.parseInt(prefs.getString(getResources().getString(R.string.theme_margin), "0"));
		} catch (Exception e) {
			margin = 0;
		}

		boolean alphabeticOrder = prefs.getBoolean(getResources().getString(R.string.app_alphabetic_order), false);

		Style style = StyleFactory.getStyle(standardScreen, prefs, bmpCestino, this, dimensioneSchermo);
		style.crea(NUMERO_PROCESSI_RUNNING, NUMERO_PROCESSI_RECENTLY, NUMERO_PROCESSI_SERVICE, margin, alphabeticOrder);

	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		crea(Integer.parseInt(prefs.getString(getResources().getString(R.string.theme_main_new), "0")));
	}
	@Override
	protected void onRestart() {
		super.onRestart();
		onCreate();
	}

	private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if ((action.equals("com.android.music.metachanged")) || (action.equals("com.android.music.playstatechanged"))) {
				updateTitle();
			}
		}
	};

	public void updateTitle() {
		TextView tv = (TextView) Main.this.findViewById(R.id.tv_title_4);
		try {
			if (MusicUtils.sService != null) {
				StringBuffer sb = new StringBuffer(MusicUtils.sService.getArtistName());
				sb.append(" - ");
				sb.append(MusicUtils.sService.getTrackName());
				tv.setText(sb.toString());
				ImageView iv = (ImageView) Main.this.findViewById(R.id.IV_art);
				Bitmap bm = MusicUtils.getArtworkQuick(this, MusicUtils.sService.getAlbumId(), 76, 76);
				if (bm != null) {
					iv.setImageBitmap(bm);
				} else {
					iv.setImageResource(R.drawable.prova);
				}
			}
		} catch (Exception e) {
		}
	}

	@Override
	protected void onStart() {
		if (prefs.getBoolean(getResources().getString(R.string.app_animation), true)) {
			final LinearLayout scrivania = (LinearLayout) this.findViewById(R.id.LL_contenitore);
			if (scrivania != null) {
				Animation hyperspaceJump = AnimationUtils.loadAnimation(this, R.anim.translate_bottom_up);
				scrivania.startAnimation(hyperspaceJump);
			}
		}
		if (Integer.parseInt(prefs.getString(getResources().getString(R.string.theme_main_new), "0")) == Style.LAYOUT_EXTENDED) {
			if (prefs.getBoolean(getResources().getString(R.string.audio_controls), false)) {
				MusicUtils.bindToService(this);
				android.content.IntentFilter f = new android.content.IntentFilter();
				f.addAction("com.android.music.metachanged");
				f.addAction("com.android.music.playstatechanged");
				registerReceiver(mStatusListener, new android.content.IntentFilter(f));
				updateTitle();
			}
		}
		super.onStart();
	}
	@Override
	protected void onStop() {
		Editor editor = prefs.edit();
		editor.putBoolean(getResources().getString(R.string.mtm_on_home), false);
		editor.commit();

		if (MusicUtils.sService != null) {
			try {
				unregisterReceiver(mStatusListener);
			} catch (Exception e) {
			}
			MusicUtils.unbindFromService(this);
		}

		super.onStop();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		if (prefs.getBoolean(getResources().getString(R.string.mtm_on_home), false)) {
			String packageName = prefs.getString(getResources().getString(R.string.home_click_default), "");
			if (packageName.equals("")) {
				PackageManager manager = Main.this.getPackageManager();
				Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
				mainIntent.addCategory(Intent.CATEGORY_HOME);
				final List<ResolveInfo> apps = manager.queryIntentActivityOptions(null, null, mainIntent, 0);
				if (apps != null) {
					ResolveInfo info = apps.get(0);
					packageName = info.activityInfo.applicationInfo.packageName;
				}
			}
			Editor editor = prefs.edit();
			editor.putBoolean(getResources().getString(R.string.mtm_on_home), false);
			editor.commit();
			Intent intentNew = new Intent(Intent.ACTION_MAIN);
			intentNew.addCategory(Intent.CATEGORY_HOME);
			intentNew.setPackage(packageName);
			try {
				startActivity(intentNew);
			} catch (Exception e) {
				Toast.makeText(this, "The home that you have choice is not compatible with the application.Change it!", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		Intent i = new Intent(Main.this, Setup.class);
		startActivityForResult(i, 1234567);

		return super.onPrepareOptionsMenu(menu);
	}

	public void prepareStartActivity(App app) {
		String packageName = app.getPackageName();
		String className = app.getClassName();
		Intent intent = null;
		if (className == null) {
			intent = Main.this.getPackageManager().getLaunchIntentForPackage(packageName);
		} else {
			ComponentName c = new ComponentName(packageName, className);
			intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setComponent(c);
			int launchFlags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED;
			intent.setFlags(launchFlags);
		}

		try {
			if (prefs.getBoolean(Main.CLOSE_ON_START_APPLICATION, true)) {
				startActivity(intent);
				finish();
			} else {
				startActivityForResult(intent, 1234);
			}
		} catch (Exception ex) {
			intent = Main.this.getPackageManager().getLaunchIntentForPackage(packageName);
			if (prefs.getBoolean(Main.CLOSE_ON_START_APPLICATION, true)) {
				startActivity(intent);
				finish();
			} else {
				startActivityForResult(intent, 1234);
			}

		}
	}
	public void prepareKillActivity(App app) {
		if (!prefs.getBoolean(PREF_KILL_SENZA_CONFERMA, false)) {
			try {
				Intent i = new Intent(Main.this, DialogoKill.class);

				String packageName = app.getPackageName();
				i.putExtra(Main.PACKAGE_NAME, packageName);
				startActivityForResult(i, 123456);
			} catch (Exception ex) {

			}
		} else {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
				killApplication2(app);
			} else {
				killApplication(app);
			}
		}
	}
	private void killApplication(App app) {

		String packageName = app.getPackageName();
		ActivityManager actvityManager = (ActivityManager) Main.this.getSystemService(ACTIVITY_SERVICE);
		actvityManager.restartPackage(packageName);
		crea(Integer.parseInt(prefs.getString(getResources().getString(R.string.theme_main_new), "0")));

	}
	private void killApplication2(App app) {

		ActivityManager activityManager = (ActivityManager) Main.this.getSystemService(ACTIVITY_SERVICE);

		Class<? extends ActivityManager> dummyClass = activityManager.getClass();
		Class<?>[] partypes = new Class<?>[]{String.class};
		Method meth;
		try {
			meth = dummyClass.getMethod("killBackgroundProcesses", partypes);
			Object[] arglist = new Object[]{app.getPackageName()};
			meth.invoke(activityManager, arglist);
		} catch (Exception e) {

		}

		crea(Integer.parseInt(prefs.getString(getResources().getString(R.string.theme_main_new), "0")));

	}

	final class InformationAlert extends Builder {

		InformationAlert(Context context, boolean primaInstallazione) {
			super(context);

			setTitle(R.string.information_title);
			setMessage(R.string.information_message);

			android.content.DialogInterface.OnClickListener installListener = new android.content.DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Main.this);
					SharedPreferences.Editor editor = prefs.edit();
					editor.putBoolean(Main.MESSAGGIO_LETTO, true);
					editor.commit();
				}
			};

			setPositiveButton(R.string.information_ok, installListener);
		}
	}
}
